#include "AppConfig.h"

QString execPath;
QString cachePath;
QString logPath;


void initAppConfigConst(){
    execPath = QCoreApplication::applicationDirPath();
    cachePath = QDir(execPath).filePath("runtime-cache");
    logPath = QDir(execPath).filePath("runtime-log");

    if(!QDir(cachePath).exists()){
        QDir().mkpath(cachePath);
    }

    if(!QDir(logPath).exists()){
        QDir().mkpath(logPath);
    }
}


void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 获取当前日期
    QString currentDate = QDateTime::currentDateTime().toString("yyyy-MM-dd");

    // 构建日志文件名
    QString logFileName = QDir(logPath).filePath("log_" + currentDate + ".txt");

    // 打开或创建log文件
    QFile logFile(logFileName);
    if (logFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
        QTextStream fileStream(&logFile);

        // 写入时间戳、消息类型、消息内容等信息到log文件
        switch (type) {
        case QtDebugMsg:
            fileStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Debug ";
            break;
        case QtInfoMsg:
            fileStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Info ";
            break;
        case QtWarningMsg:
            fileStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Warning ";
            break;
        case QtCriticalMsg:
            fileStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Critical ";
            break;
        case QtFatalMsg:
            fileStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Fatal ";
            break;
        }

        fileStream << msg << Qt::endl;

        logFile.close();
    }

    // 输出到控制台
    QTextStream consoleStream(stdout);
    switch (type) {
    case QtDebugMsg:
        consoleStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Debug ";
        break;
    case QtInfoMsg:
        consoleStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Info ";
        break;
    case QtWarningMsg:
        consoleStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Warning ";
        break;
    case QtCriticalMsg:
        consoleStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Critical ";
        break;
    case QtFatalMsg:
        consoleStream << QDateTime::currentDateTime().toString("hh:mm:ss ") << "Fatal ";
        break;
    }

    consoleStream << msg << Qt::endl;
}
